package com.kede.api.order.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kede.PubConst;
import com.kede.api.ienum.UserMoneyType;
import com.kede.api.order.service.ITransportManageService;
import com.kede.api.order.service.IUserService;
import com.kede.domain.*;
import com.kede.pojo.GoodValidFailStatus;
import com.kede.pojo.ResHttp;
import com.kede.pojo.TransPortStatusEnum;
import com.kede.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author:Pr.li
 * @Date: create in 2023/10/14 16:33
 */
@Service
public class TransportManageServiceImpl implements ITransportManageService {

    @Resource
    private TransportService transportService;

    @Resource
    private PackageService packageService;

    @Resource
    private ZhiOrderGoodsListService zhiOrderGoodsListService;

    @Resource
    private ZhiGoodValidFailService zhiGoodValidFailService;

    @Override
    public ResHttp sureComplte(Integer transportId) {
        TransportDomain transport = transportService.getById(transportId);
        if (!transport.getStatus().equals(TransPortStatusEnum.Compting.getStatus())){
            return ResHttp.failMsg("非法操作");
        }
        Map<Integer,ZhiGoodValidDomain> cerVailMap = new HashMap<>();
        String[] split = transport.getPackages().split(",");
        LambdaQueryWrapper<ZhiGoodValidFailDomain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZhiGoodValidFailDomain::getTransportId,transportId);
        List<ZhiGoodValidFailDomain> fialGoods = zhiGoodValidFailService.list(queryWrapper);
        //验证失败的物品id
        List<Integer> fialGoodIds = fialGoods.stream().map(ZhiGoodValidFailDomain::getGoodId).collect(Collectors.toList());
        //验证失败的物品记录id
        List<Integer> fialGoodLogIds = fialGoods.stream().map(ZhiGoodValidFailDomain::getId).collect(Collectors.toList());
        for (String pckId : split) {
            PackageDomain pkg = packageService.getById(Integer.valueOf(pckId));
            if (pkg==null){
                continue;
            }
            if(pkg.getStoreId()!=null){
                String[] goodIds = pkg.getGoodIds().split(",");
                List<String> list = new ArrayList<>(Arrays.asList(goodIds));
                List<Integer> collect = list.stream().map(Integer::valueOf).collect(Collectors.toList());
                List<ZhiOrderGoodsListDomain> goodList = zhiOrderGoodsListService.listByIds(collect);
                for (ZhiOrderGoodsListDomain goodsListDomain : goodList) {
                    calcCerVailInfo(pkg,cerVailMap,goodsListDomain,transportId,fialGoodIds);
                }
            }
        }
        ITransportManageService bean = SpringUtil.getBean(ITransportManageService.class);
        bean.setComplteMoney(cerVailMap,transportId.toString(),fialGoodLogIds);
        return ResHttp.ok();
    }

    /**
     *
     * @param pkg 该物品所属包
     * @param cerVailMap
     * @param good
     * @param transportId
     * @param failGoodList
     */
    private void calcCerVailInfo(PackageDomain pkg,Map<Integer,ZhiGoodValidDomain> cerVailMap,ZhiOrderGoodsListDomain good,Integer transportId,List<Integer> failGoodList){
        if(pkg.getStoreId() != null && !pkg.getStoreId().equals(PubConst.ZERO)){
            ZhiUserCertifiedDomain cerInfo = zhiUserCertifiedService.getById(pkg.getStoreId());
            if (!cerVailMap.containsKey(pkg.getStoreId())) {
                ZhiGoodValidDomain initGoodValid = getInitGoodValid(cerInfo.getStoreName(),transportId);
                initGoodValid.setStoreId(pkg.getStoreId());
                initGoodValid.setUserId(cerInfo.getUserId());
                cerVailMap.put(pkg.getStoreId(),initGoodValid);
            }
            ZhiGoodValidDomain zhiGoodValidDomain = cerVailMap.get(pkg.getStoreId());
            //统计数量 和金额
            if(failGoodList.contains(good.getId())){
                zhiGoodValidDomain.setFail(zhiGoodValidDomain.getFail() + 1);
            }else{
                zhiGoodValidDomain.setPass(zhiGoodValidDomain.getPass() + 1);
                zhiGoodValidDomain.setRealMoney(zhiGoodValidDomain.getRealMoney().add(good.getDefaultStoreMoney()));
            }
            zhiGoodValidDomain.setNum(zhiGoodValidDomain.getNum() + 1);
            zhiGoodValidDomain.setShouldMoney(zhiGoodValidDomain.getShouldMoney().add(good.getDefaultStoreMoney()));
        }
        if (pkg.getQuId() != null && !pkg.getQuId().equals(PubConst.ZERO)){
            ZhiUserCertifiedDomain cerInfo = zhiUserCertifiedService.getById(pkg.getQuId());
            if (!cerVailMap.containsKey(pkg.getQuId())) {
                ZhiGoodValidDomain initGoodValid = getInitGoodValid(cerInfo.getStoreName(),transportId);
                initGoodValid.setQuId(pkg.getQuId());
                initGoodValid.setUserId(cerInfo.getUserId());
                cerVailMap.put(pkg.getQuId(),initGoodValid);
            }
            ZhiGoodValidDomain zhiGoodValidDomain = cerVailMap.get(pkg.getQuId());
            //统计数量 和金额
            if(failGoodList.contains(good.getId())){
                zhiGoodValidDomain.setFail(zhiGoodValidDomain.getFail() + 1);
                zhiGoodValidDomain.setQuId(pkg.getQuId());
            }else{
                zhiGoodValidDomain.setPass(zhiGoodValidDomain.getPass() + 1);
                zhiGoodValidDomain.setRealMoney(zhiGoodValidDomain.getRealMoney().add(good.getDefaultQuMoney()));
            }
            zhiGoodValidDomain.setNum(zhiGoodValidDomain.getNum() + 1);
            zhiGoodValidDomain.setShouldMoney(zhiGoodValidDomain.getShouldMoney().add(good.getDefaultQuMoney()));
        }
        if (pkg.getShiId() != null && !pkg.getShiId().equals(PubConst.ZERO)){
            ZhiUserCertifiedDomain cerInfo = zhiUserCertifiedService.getById(pkg.getShiId());
            if (!cerVailMap.containsKey(pkg.getShiId())) {
                ZhiGoodValidDomain initGoodValid = getInitGoodValid(cerInfo.getStoreName(),transportId);
                initGoodValid.setShiId(pkg.getShiId());
                initGoodValid.setUserId(cerInfo.getUserId());
                cerVailMap.put(pkg.getShiId(),initGoodValid);
            }
            ZhiGoodValidDomain zhiGoodValidDomain = cerVailMap.get(pkg.getShiId());
            //统计数量 和金额
            if(failGoodList.contains(good.getId())){
                zhiGoodValidDomain.setFail(zhiGoodValidDomain.getFail() + 1);
                zhiGoodValidDomain.setShiId(pkg.getShiId());
            }else{
                zhiGoodValidDomain.setPass(zhiGoodValidDomain.getPass() + 1);
                zhiGoodValidDomain.setRealMoney(zhiGoodValidDomain.getRealMoney().add(good.getDefaultShiMoney()));
            }
            zhiGoodValidDomain.setNum(zhiGoodValidDomain.getNum() + 1);
            zhiGoodValidDomain.setShouldMoney(zhiGoodValidDomain.getShouldMoney().add(good.getDefaultShiMoney()));
        }

    }

    /**
     * 需要设置 id 和 name
     * @return
     */
    private ZhiGoodValidDomain getInitGoodValid(String cerName,Integer transportId){
        ZhiGoodValidDomain goodValidDomain = new ZhiGoodValidDomain();
        goodValidDomain.setCreateTime(LocalDateTime.now());
        goodValidDomain.setFail(0);
        goodValidDomain.setNum(0);
        goodValidDomain.setPass(0);
        //店铺的名称
        goodValidDomain.setName(cerName);
        BigDecimal zero = new BigDecimal("0");
        goodValidDomain.setRealMoney(zero);
        goodValidDomain.setShouldMoney(zero);
        goodValidDomain.setTransportId(transportId);
        return goodValidDomain;
    }


    @Resource
    private IUserService userManageService;

    @Resource
    private ZhiUserCertifiedService zhiUserCertifiedService;

    @Resource
    private ZhiGoodValidService zhiGoodValidService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setComplteMoney(Map<Integer,ZhiGoodValidDomain> cerVailMap,String transportId,List<Integer> fialGoodLogIds){
        cerVailMap.forEach((cerId, zhiGoodValidDomain) -> {
            //1 加钱
            userManageService.actionMoney(zhiGoodValidDomain.getUserId(),zhiGoodValidDomain.getRealMoney(),transportId,UserMoneyType.VAILD);
            //2 生成失败统计
            zhiGoodValidService.save(zhiGoodValidDomain);
            //3 扣验收款
            ZhiUserCertifiedDomain certifiedDomain = zhiUserCertifiedService.getById(cerId);
            certifiedDomain.setValidMoney(certifiedDomain.getValidMoney().subtract(zhiGoodValidDomain.getShouldMoney()));
            zhiUserCertifiedService.updateById(certifiedDomain);
        });
        //4运输单 已结算
        TransportDomain transportDomain = transportService.getById(transportId);
        transportDomain.setStatus(TransPortStatusEnum.Compted.getStatus());
        transportService.updateById(transportDomain);
        //5 修改失败记录的状态
        fialGoodLogIds.forEach(failGoodLogId -> {
            ZhiGoodValidFailDomain byId = zhiGoodValidFailService.getById(failGoodLogId);
            byId.setStatus(GoodValidFailStatus.SURE.getStatus());
            zhiGoodValidFailService.updateById(byId);
        });
    }

    @Override
    public ResHttp showInfoComplte(Integer transportId) {
        TransportDomain transport = transportService.getById(transportId);
        if (!transport.getStatus().equals(TransPortStatusEnum.Compting.getStatus())){
            return ResHttp.failMsg("非法操作");
        }
        Map<Integer,ZhiGoodValidDomain> cerVailMap = new HashMap<>();
        String[] split = transport.getPackages().split(",");
        LambdaQueryWrapper<ZhiGoodValidFailDomain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZhiGoodValidFailDomain::getTransportId,transportId);
        List<ZhiGoodValidFailDomain> fialGoods = zhiGoodValidFailService.list(queryWrapper);
        //验证失败的物品id
        List<Integer> fialGoodIds = fialGoods.stream().map(ZhiGoodValidFailDomain::getGoodId).collect(Collectors.toList());
        for (String pckId : split) {
            PackageDomain pkg = packageService.getById(Integer.valueOf(pckId));
            if (pkg==null){
                continue;
            }
            if(pkg.getStoreId()!=null){
                String[] goodIds = pkg.getGoodIds().split(",");
                List<String> list = new ArrayList<>(Arrays.asList(goodIds));
                List<Integer> collect = list.stream().map(Integer::valueOf).collect(Collectors.toList());
                List<ZhiOrderGoodsListDomain> goodList = zhiOrderGoodsListService.listByIds(collect);
                for (ZhiOrderGoodsListDomain goodsListDomain : goodList) {
                    calcCerVailInfo(pkg,cerVailMap,goodsListDomain,transportId,fialGoodIds);
                }
            }
        }
        return ResHttp.okData(cerVailMap.values());
    }
}
